﻿#include "ComputerRoomFile.h"

ComputerRoomFile::ComputerRoomFile()
{
	this->init();// 初始化（从文件读)
}
ComputerRoomFile::~ComputerRoomFile()
{
	this->updateComputerRoomData();
}

void ComputerRoomFile::showInfo()
{
	for_each(this->m_vComputerRoomData.begin(), this->m_vComputerRoomData.end(),
		[](const ComputerRoom& com) {
			cout << com.m_Id << "号机房的最大数量为：" << com.m_MaxNum
				<< "，当前可预约数量为：" << com.m_CurrentNum << endl;
	});
}

// 初始化（从文件读）
void ComputerRoomFile::init()
{
	this->m_vComputerRoomData.clear();

	ifstream ifs;
	//加载机房文件信息
	ifs.open(COMPUTER_FILE, ios::in);
	if (!ifs.is_open())
	{
		cout << "机房文件不存在！" << endl;
		ifs.close();
		return;
	}
	int id;
	int maxNum;
	int currentNum;
	while (ifs >> id && ifs >> maxNum && ifs >> currentNum)
	{
		//cout << id << "号机房的最大数量为：" << maxNum << "，当前数量为：" << currentNum << endl;
		ComputerRoom com(id, maxNum, currentNum);
		this->m_vComputerRoomData.push_back(com);
	}
	ifs.close();
}

// 更新机房数据（向文件中写）
void ComputerRoomFile::updateComputerRoomData()
{
	ofstream ofs;
	ofs.open(COMPUTER_FILE, ios::out);
	for (vector<ComputerRoom>::iterator it = this->m_vComputerRoomData.begin(); it != this->m_vComputerRoomData.end(); it++)
	{
		ofs << it->m_Id << " " << it->m_MaxNum << " " << it->m_CurrentNum << endl;
	}
	ofs.close();
}

// 根据id增加或减少机器数量
void ComputerRoomFile::updateCurrentNumById(int id, int changeNum)
{
	this->m_vComputerRoomData[id - 1].m_CurrentNum += changeNum;
}

// 重置机房数据
void ComputerRoomFile::resetComputerRoomData()
{
	for (vector<ComputerRoom>::iterator it = this->m_vComputerRoomData.begin(); it != this->m_vComputerRoomData.end(); it++)
	{
		it->m_CurrentNum = it->m_MaxNum;
	}
}